package com.example.sq.service;

import com.example.sq.mapper.MenuMapper;
import com.example.sq.mapper.RoleMapper;
import com.example.sq.mapper.UserMapper;
import com.example.sq.model.domain.AuthUser;
import com.example.sq.model.entity.Menu;
import com.example.sq.model.entity.Role;
import com.example.sq.model.entity.User;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        List<User> userList = userMapper.selectUserByUsername(username);
        if (userList == null || userList.isEmpty()){
            throw new RuntimeException("该用户名不存在");
        }
        // 如果返回多个用户直接抛异常
        if (userList.size()>1){
            throw new RuntimeException("账号异常,请联系管理员");
        }
        // 如果返回一个用户封装 UserDetail 返回
        User user = userList.get(0);
        // 获取用户角色信息
        List<Role> roleList = roleMapper.selectRoleByUserId(user.getId());
        if (roleList!=null && !roleList.isEmpty()){
            user.setRoles(roleList);
            List<Menu> menuList = new ArrayList<>();
            roleList.forEach(role -> {
                menuList.addAll(menuMapper.selectMenuByRoleId(role.getId()));
            });
            user.setMenus(menuList);
        }
        return new AuthUser(user);
    }

}




